//
//  JsbSDK.m
//  Game105Client-mobile
//
//  Created by Developer001 on 2025/3/26.
//

#import <Foundation/Foundation.h>
#import "JsbSDK.h"

#include "platform/apple/JsbBridge.h"

#include "application/ApplicationManager.h" // 找cocos线程
#import <cocos/bindings/jswrapper/SeApi.h> // OC调用JS

@implementation JsbSDK

static JsbSDK* instance = nil;

- (void)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"JsbSDK launched");
    instance = self;
    instance.viewController = [application delegate].window.rootViewController;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance.handlerDictionary = [NSMutableDictionary dictionary];
    });
    
    static ICallback cb = ^void (NSString* _arg0, NSString* _arg1){
        [instance dispatchMsg:_arg0 withArg:_arg1];
    };
    
    JsbBridge* m = [JsbBridge sharedInstance];
    [m setCallback:cb];
}


+ (void)onMsg:(NSString *)msgName handler:(void (^)(NSString *))callback {
    if (callback && msgName) {
        [instance.handlerDictionary setObject:callback forKey:msgName];
    }
}

+ (void)sendMsg:(NSString *)msgName args:(NSDictionary *)dictionary {
//    NSLog(@"sendMsg %@ %@", msgName, dictionary);
    NSString *str = [JsbSDK DictionaryToString:dictionary];
    [[JsbBridge sharedInstance] sendToScript:msgName arg1: str];
}

- (void)dispatchMsg:(NSString *)msgName withArg:(NSString *)arg {
//    NSLog(@"@dispatchMsg %@ %@", msgName, arg);
    void (^callback)(NSString *) = [self.handlerDictionary objectForKey:msgName];
    if (callback) {
        callback(arg);
    } else {
        NSLog(@"No handler for msgName: %@", msgName);
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [JsbSDK sendMsg:@"JsbSDKManager.applicationDidBecomeActive" args:@{}];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [JsbSDK sendMsg:@"JsbSDKManager.applicationWillResignActive" args:@{}];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [JsbSDK sendMsg:@"JsbSDKManager.applicationDidEnterBackground" args:@{}];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [JsbSDK sendMsg:@"JsbSDKManager.applicationWillEnterForeground" args:@{}];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [JsbSDK sendMsg:@"JsbSDKManager.applicationWillTerminate" args:@{}];
}

+ (NSString *)DictionaryToString:(NSDictionary *)dictionary {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
    if (!jsonData) {
        NSLog(@"Error: NSDictionary to jsonData: %@", error);
        return nil;
    }
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


@end
